const express = require("express");
const router = express.Router();
var Teacher = require("../models/teacher.js");
var Student = require("../models/student.js");
var Class = require("../models/class.js");
var Notice = require("../models/notice.js");
const Check = require("../modules/check.js")
//发布公告
router.post("/publish",Check.login, function (req, res, next) {
    var data = req.body.data;
    Notice.publish(data, function (err, result) {
        if (err) {
            res.json({ code: 201, message: err.message })
            return;
        }
        res.json({ code: 200, message: "发布公告成功" })
    })
})

//进入班级信息页面
router.get("/classmsg",Check.login, function (req, res, next) {
    var filter = {
        teacherId: req.session.user._id,
    }
    Class.find().then(function () {
        var className = Class.find(filter).sort({ createTime: -1 });

        Promise.all([className]).then(function (result) {
            res.render("classmsg", {
                user: req.session.user,
                classes: JSON.stringify(result[0]),
            })
        }).catch(function (err) {
            res.json({ code: 201, message: err });
        })
    }).catch(function (err) {
        res.json({ code: 201, message: err });
    })
})

//进入添加学生页面
router.get("/addstudent", Check.login,function (req, res, next) {
    res.render("teachers/addstudent", {
        account: req.session.user.account,
        user: req.session.user,
    })
})
//添加学生
router.post("/addstudent",Check.login, function (req, res, next) {
    var data = req.body.data;

    Student.addstudent(data, function (err, result) {
        if (err) {
            res.json({ code: 201, message: err.message })
            return;
        }
        res.json({ code: 200, message: "添加成功" })
    })
})

//进入添加班级页面
router.get("/addclass",Check.login, function (req, res, next) {
    res.render("teachers/addclass", {

        user: req.session.user,
    })
})
//添加班级
router.post("/addclass", Check.login,function (req, res, next) {
    var data = req.body.data;
    Class.addclass(data, function (err, result) {
        if (err) {
            res.json({ code: 201, message: err.message });
            return;
        }
        res.json({ code: 200, message: "添加成功" })
    })
})
router.post("/deletestudent",function(req,res,next){
    var studentNo = req.body.studentNo;
    Student.deletestudent(studentNo,function(err,result){
        if (err) {
            res.json({ code: 201, message: err.message });
            return;
        }
        res.json({ code: 200, message: "删除成功" })
    })
})

module.exports = router;